package com.boruan.qq.zxgylibrary.ui.activities;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.webkit.JavascriptInterface;
import android.webkit.SslErrorHandler;
import android.webkit.ValueCallback;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.boruan.qq.zxgylibrary.R;
import com.boruan.qq.zxgylibrary.R2;
import com.boruan.qq.zxgylibrary.base.BaseActivity;
import com.boruan.qq.zxgylibrary.constants.ConstantInfo;
import com.boruan.qq.zxgylibrary.utils.CustomDialog;
import com.boruan.qq.zxgylibrary.utils.NavigateUtils;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by 崔琦 on 2019/8/6.
 * des: 购物车页面
 */

public class ShoppingCarActivity extends BaseActivity {
    @BindView(R2.id.ll_add_web)
    LinearLayout llAddWeb;
    @BindView(R2.id.ll_no_data)
    LinearLayout llNoData;

    private CustomDialog dialog;
    private PopupWindow confirmPop;

    @Override
    protected int getLayoutId() {
        if (Build.VERSION.SDK_INT >= 21) {
            View decorView = getWindow().getDecorView();
            decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        }
        return R.layout.drug_activity_shopping_car;
    }

    @Override
    protected void init(Bundle savedInstanceState) {
        dialog = new CustomDialog(this, R.style.CustomDialog);
        dialog.show();
        initCommonWeb(ConstantInfo.baseUrl + "shoppingCart?type=android&token=" + ConstantInfo.h5UserToken);

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        if (commonWeb != null){
            commonWeb.reload();//重新刷新页面
        }
    }

    /**
     * 初始化web
     */
    @SuppressLint("JavascriptInterface")
    private void initCommonWeb(final String richText){
        commonWeb.loadUrl(richText);
        commonWeb.addJavascriptInterface(ShoppingCarActivity.this, "control");
        commonWeb.setWebViewClient(new WebViewClient(){
            @Override
            public void onPageFinished(WebView view, String url) {
                super.onPageFinished(view, url);
                dialog.dismiss();
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
                //dialog.show();
            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();//接受所有网站的证书，忽略SSL错误
                
            }

            @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onReceivedError(WebView view, WebResourceRequest webResourceRequest, WebResourceError webResourceError) {
                super.onReceivedError(view, webResourceRequest, webResourceError);
                if (webResourceRequest.isForMainFrame()) {
//					view.loadUrl("about:blank");// 避免出现默认的错误界面
//                    Toast.makeText(ShoppingCarActivity.this, "网络加载异常，请稍后重试！", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
                super.onReceivedError(view, errorCode, description, failingUrl);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    return;
                }
//				view.loadUrl("about:blank");// 避免出现默认的错误界面
//                Toast.makeText(ShoppingCarActivity.this, "网络加载异常，请稍后重试！", Toast.LENGTH_SHORT).show();
            }
			
			@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
            @Override
            public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse errorResponse) {
                super.onReceivedHttpError(view, request, errorResponse);
                // 这个方法在 android 6.0才出现
                int statusCode = errorResponse.getStatusCode();
                if (404 == statusCode || 500 == statusCode) {
//                    view.loadUrl("about:blank");// 避免出现默认的错误界面
                }
            }
        });
        llAddWeb.addView(commonWeb);
    }

    @JavascriptInterface
    public void clickEnterPharmacy(String id){//点击购物车的商品进入药店详情查看
        Log.i("id",id + "lala");
        Intent intent = new Intent(ShoppingCarActivity.this, PharmacyHomePageActivity.class);
        intent.putExtra("id",id);
        startActivity(intent);
    }

    @JavascriptInterface
    public void helpMePurchaseDrug(final String id,final String shopName){//点击帮我买药，弹出确认授权框。id为药店shopId
        Log.i("id",id + "lala");
        //弹出用户确认授权框
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                authorizationPopWindow(id,shopName);
            }
        });
    }

    @OnClick({R2.id.tv_close_shop, R2.id.empty_shop_car})
    public void onViewClicked(View view) {
        int i = view.getId();
        if (i == R.id.tv_close_shop) {
            finish();

        } else if (i == R.id.empty_shop_car) {
            confirmPopWindow();
        }
    }

    /**
     * 购买确认授权框
     * */
    private PopupWindow authorizationPop;
    public void authorizationPopWindow(final String shopId,String shopName){
        authorizationPop = new PopupWindow();
        View convertView = LayoutInflater.from(this).inflate(R.layout.drug_pop_authorization_layout,null);
        TextView tvContent = (TextView)convertView.findViewById(R.id.tv_content);
        TextView tvCancel = (TextView)convertView.findViewById(R.id.tv_cancel);
        TextView tvOk = (TextView)convertView.findViewById(R.id.tv_ok);
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                authorizationPop.dismiss();
            }
        });

        tvContent.setText(shopName + ConstantInfo.shopNotice);

        tvOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                authorizationPop.dismiss();
                new NavigateUtils(ShoppingCarActivity.this).navigateConfirmOrderActivity(shopId,121);
//                Intent intent = new Intent(ShoppingCarActivity.this,ConfirmOrderActivity.class);
//                intent.putExtra("shopId",shopId);
//                startActivityForResult(intent,121);
            }
        });

        authorizationPop.setContentView(convertView);

        authorizationPop.setWidth(ConstantInfo.screenWidth - 280);
        authorizationPop.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        authorizationPop.setBackgroundDrawable(new ColorDrawable(0x00000000));
        authorizationPop.setTouchable(true);
        authorizationPop.setOutsideTouchable(false);
        /** 设置popupWindow动画 */
        authorizationPop.setAnimationStyle(R.style.style_down_to_up_animation);
        //不设置焦点的话点击外面dismiss的同时会响应外层的触摸事件
        backgroundAlpha(0.3f);
        authorizationPop.setFocusable(false);
        authorizationPop.showAtLocation(findViewById(R.id.ll_add_web), Gravity.CENTER,0,0);
        authorizationPop.setOnDismissListener(new poponDismissListener());
    }

    private void confirmPopWindow(){
        confirmPop = new PopupWindow();
        View convertView = LayoutInflater.from(this).inflate(R.layout.drug_pop_empty_shop_car,null);
        TextView tvCancel = (TextView)convertView.findViewById(R.id.tv_cancel);
        TextView tvOk = (TextView)convertView.findViewById(R.id.tv_ok);
        tvCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                confirmPop.dismiss();
            }
        });

        tvOk.setOnClickListener(new View.OnClickListener() {
            @RequiresApi(api = Build.VERSION_CODES.KITKAT)
            @Override
            public void onClick(View view) {
                confirmPop.dismiss();
                commonWeb.evaluateJavascript("window.emptyGoodInCar()", new ValueCallback<String>() {
                    @Override
                    public void onReceiveValue(String s) {
                        Log.i("error",s);
                    }
                });
            }
        });
        confirmPop.setContentView(convertView);

        confirmPop.setWidth(ConstantInfo.screenWidth - getPxFromDp(80));
        confirmPop.setHeight(WindowManager.LayoutParams.WRAP_CONTENT);
        confirmPop.setBackgroundDrawable(new ColorDrawable(0x00000000));
        confirmPop.setTouchable(true);
        confirmPop.setOutsideTouchable(false);
        /** 设置popupWindow动画 */
        confirmPop.setAnimationStyle(R.style.style_down_to_up_animation);
        //不设置焦点的话点击外面dismiss的同时会响应外层的触摸事件
        backgroundAlpha(0.3f);
        confirmPop.setFocusable(false);
        confirmPop.showAtLocation(findViewById(R.id.ll_add_web), Gravity.CENTER,0,0);
        confirmPop.setOnDismissListener(new poponDismissListener());
    }

    /**
     * 重写activity中dispatchTouchEvent,在里面判断popupWindow是否显示来决定是否往下分发事件。
     * */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if(confirmPop != null && confirmPop.isShowing()){
            return false;
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 得到dp转化成的px
     * */
    public int getPxFromDp(float dip) {
        float result = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dip, getResources().getDisplayMetrics());
        return (int) result;
    }

    /**
     * PopupWindow背景变暗
     */
    public void backgroundAlpha(float bgAlpha) {
        WindowManager.LayoutParams lp = getWindow().getAttributes();
        lp.alpha = bgAlpha; //0.0-1.0
        getWindow().setAttributes(lp);
    }

    class poponDismissListener implements PopupWindow.OnDismissListener {
        @Override
        public void onDismiss() {
            // TODO Auto-generated method stub
            backgroundAlpha(1f);
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (confirmPop != null && confirmPop.isShowing()){
            confirmPop.dismiss();
            return false;
        }else {
            if (keyCode == KeyEvent.KEYCODE_BACK && commonWeb.canGoBack()) {
                commonWeb.goBack();
                return true;
            }
            return super.onKeyDown(keyCode, event);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 121 && resultCode == 122){
            if (commonWeb != null){
                commonWeb.reload();//重新刷新页面
            }
        }
    }

    @Override
    protected void onDestroy() {
        Log.i("测试","ondes");
        if (commonWeb != null) {
            //加载null内容
            commonWeb.loadDataWithBaseURL(null, "", "text/html", "utf-8", null);
            //清除历史记录
            commonWeb.clearHistory();
            //移除WebView
            ((ViewGroup) commonWeb.getParent()).removeView(commonWeb);
            //销毁VebView
            commonWeb.destroy();
            //WebView置为null
            commonWeb = null;
        }
        super.onDestroy();
    }

}
